package scc.project.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import scc.project.entity.Employee;
import scc.project.entity.vo.JsonVo;
import scc.project.service.EmployeeService;
import scc.project.util.HttpUtil;

import javax.servlet.http.HttpSession;

/**
 * <h5>用户的控制器</h5>
 * <p>关于用户的请求都放在这控制器里面</p>
 *
 * @author 陈圳佳
 *         日期：2015/6/22
 */
@Controller
public class EmpController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登入功能，需要使用 Ajax 访问，返回JSON
     *
     * @param username 用户名
     * @param password 密码
     */
    @ResponseBody
    @RequestMapping(value = "/sign/in/{username}/{password}", method = RequestMethod.GET)
    public JsonVo sign(@PathVariable("username") String username,
                       @PathVariable("password") String password,
                       HttpSession session) {
        JsonVo jsonVo = new JsonVo();
        try {
            Employee emp = employeeService.getEmp(username, password);
            jsonVo.setStatus(true);
            jsonVo.addValue("emp", emp).addValue("url", "manage/home.html");
            HttpUtil.saveEmp(session, emp);
        } catch (Exception e) {
            jsonVo.setMsg(e.getMessage()).setStatus(false);
            e.printStackTrace();
        }
        return jsonVo;
    }

    /**
     * 登出功能，需要使用 AJAX 访问
     */
    @ResponseBody
    @RequestMapping(value = "/sign/out", method = RequestMethod.DELETE)
    public JsonVo out(HttpSession session) {
        JsonVo jsonVo = new JsonVo();
        session.removeAttribute(HttpUtil.SESSION_USER);
        jsonVo.setStatus(true);
        jsonVo.addValue("url", "login.html");
        return jsonVo;
    }

}
